<template>
  <div class="simple-sql-editor">
    <!-- 编辑器工具栏 -->
    <div class="editor-toolbar">
      <div class="toolbar-left">
        <el-button-group>
          <el-button 
            size="small" 
            @click="formatSQL" 
            :disabled="!modelValue || loading"
            title="格式化SQL"
          >
            <el-icon><Document /></el-icon>
            格式化
          </el-button>
          <el-button
            size="small"
            @click="clearEditor"
            :disabled="loading"
            title="清空编辑器"
          >
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
        </el-button-group>

        <!-- 编辑器尺寸调整按钮 -->
        <el-button-group style="margin-left: 8px;">
          <el-button
            size="small"
            @click="setEditorSize('mini')"
            title="迷你尺寸 (80px) - 约一行高度"
            :type="editorHeight <= 100 ? 'primary' : ''"
          >
            迷你
          </el-button>
          <el-button
            size="small"
            @click="setEditorSize('small')"
            title="小尺寸 (200px)"
            :type="editorHeight > 100 && editorHeight <= 250 ? 'primary' : ''"
          >
            小
          </el-button>
          <el-button
            size="small"
            @click="setEditorSize('medium')"
            title="中尺寸 (400px)"
            :type="editorHeight > 250 && editorHeight <= 450 ? 'primary' : ''"
          >
            中
          </el-button>
          <el-button
            size="small"
            @click="setEditorSize('large')"
            title="大尺寸 (600px)"
            :type="editorHeight > 450 ? 'primary' : ''"
          >
            大
          </el-button>
        </el-button-group>
      </div>
      <div class="toolbar-right">
        <el-tag v-if="editorReady && !loading" type="success" size="small">
          <el-icon><Check /></el-icon>
          SQL编辑器就绪
        </el-tag>
        <el-tag v-else-if="loading" type="warning" size="small">
          <el-icon class="is-loading"><Loading /></el-icon>
          初始化中...
        </el-tag>
        <el-tag v-else type="danger" size="small">
          <el-icon><Close /></el-icon>
          未就绪
        </el-tag>
      </div>
    </div>
    
    <!-- Monaco编辑器容器 -->
    <div
      ref="editorContainer"
      class="editor-container"
      :style="{ height: editorHeight + 'px' }"
      v-loading="loading"
      element-loading-text="正在初始化SQL编辑器..."
    ></div>

    <!-- 拖拽调整条 -->
    <div
      class="resize-handle"
      @mousedown="startResize"
      title="拖拽调整编辑器高度"
    >
      <div class="resize-line"></div>
    </div>
    
    <!-- 编辑器状态栏 -->
    <div class="editor-footer">
      <div class="footer-left">
        <span class="editor-info">
          字符数: {{ modelValue ? modelValue.length : 0 }}
        </span>
        <span class="editor-info">
          行数: {{ lineCount }}
        </span>
        <span class="editor-info">
          高度: {{ editorHeight }}px
        </span>
      </div>
      <div class="footer-right">
        <el-tag size="small" type="info">SQL</el-tag>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Document, Delete, Check, Close, Loading
} from '@element-plus/icons-vue'
import loader from '@monaco-editor/loader'

// Props定义
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '400px'
  },
  placeholder: {
    type: String,
    default: '-- 请输入SQL查询语句...'
  }
})

// Emits定义
const emit = defineEmits(['update:modelValue', 'change', 'ready'])

// 响应式数据
const editorContainer = ref(null)
const loading = ref(true)
const editorReady = ref(false)
const editorHeight = ref(400) // 可调整的编辑器高度
const isResizing = ref(false)

let editorInstance = null
let startY = 0
let startHeight = 0

// 基础SQL语言注册函数
const registerBasicSQLLanguage = (monaco) => {
  // 检查是否已经注册了SQL语言
  const existingLanguages = monaco.languages.getLanguages()
  const sqlLanguageExists = existingLanguages.some(lang => lang.id === 'sql')

  if (!sqlLanguageExists) {
    monaco.languages.register({ id: 'sql' })
  }

  // 基础SQL关键字（保守方案 - 约20个核心关键字）
  const sqlKeywords = [
    'SELECT', 'FROM', 'WHERE', 'INSERT', 'UPDATE', 'DELETE',
    'CREATE', 'DROP', 'ALTER', 'TABLE', 'INDEX', 'VIEW',
    'JOIN', 'LEFT', 'RIGHT', 'INNER', 'OUTER', 'ON',
    'GROUP', 'ORDER', 'BY', 'HAVING', 'LIMIT', 'OFFSET',
    'AND', 'OR', 'NOT', 'IN', 'EXISTS', 'LIKE', 'BETWEEN',
    'IS', 'NULL', 'DISTINCT', 'UNION', 'ALL'
  ]

  // 基础MySQL函数（保守方案 - 约15个常用函数）
  const sqlFunctions = [
    'COUNT', 'SUM', 'AVG', 'MAX', 'MIN',
    'NOW', 'DATE', 'TIME', 'YEAR', 'MONTH', 'DAY',
    'CONCAT', 'LENGTH', 'UPPER', 'LOWER'
  ]

  // 基础数据类型（保守方案 - 约10个常用类型）
  const sqlTypes = [
    'INT', 'VARCHAR', 'TEXT', 'DATE', 'DATETIME', 'TIMESTAMP',
    'DECIMAL', 'FLOAT', 'BOOLEAN', 'BLOB'
  ]

  // 设置语法高亮
  monaco.languages.setMonarchTokensProvider('sql', {
    keywords: sqlKeywords,
    functions: sqlFunctions,
    types: sqlTypes,
    operators: ['=', '>', '<', '!', '~', '?', ':', '==', '<=', '>=', '!=', '&&', '||'],
    symbols: /[=><!~?:&|+\-*\/\^%]+/,

    tokenizer: {
      root: [
        [/[a-z_$][\w$]*/, {
          cases: {
            '@keywords': 'keyword',
            '@functions': 'predefined',
            '@types': 'type',
            '@default': 'identifier'
          }
        }],
        [/[A-Z_$][\w$]*/, {
          cases: {
            '@keywords': 'keyword',
            '@functions': 'predefined',
            '@types': 'type',
            '@default': 'identifier'
          }
        }],
        [/[ \t\r\n]+/, 'white'],
        [/--.*$/, 'comment'],
        [/\/\*/, 'comment', '@comment'],
        [/'([^'\\]|\\.)*$/, 'string.invalid'],
        [/'/, 'string', '@string'],
        [/"([^"\\]|\\.)*$/, 'string.invalid'],
        [/"/, 'string', '@string_double'],
        [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
        [/\d+/, 'number'],
        [/@symbols/, { cases: { '@operators': 'operator', '@default': '' } }],
        [/[;,.]/, 'delimiter'],
        [/[()]/, '@brackets']
      ],
      comment: [
        [/[^\/*]+/, 'comment'],
        [/\/\*/, 'comment', '@push'],
        [/\*\//, 'comment', '@pop'],
        [/[\/*]/, 'comment']
      ],
      string: [
        [/[^\\']+/, 'string'],
        [/\\./, 'string.escape'],
        [/'/, 'string', '@pop']
      ],
      string_double: [
        [/[^\\"]+/, 'string'],
        [/\\./, 'string.escape'],
        [/"/, 'string', '@pop']
      ]
    }
  })

  // 注册智能补全（保守方案 - 基础补全）
  monaco.languages.registerCompletionItemProvider('sql', {
    provideCompletionItems: (model, position) => {
      const word = model.getWordUntilPosition(position)
      const range = {
        startLineNumber: position.lineNumber,
        endLineNumber: position.lineNumber,
        startColumn: word.startColumn,
        endColumn: word.endColumn
      }

      const suggestions = []

      // 添加关键字补全
      sqlKeywords.forEach(keyword => {
        suggestions.push({
          label: keyword,
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: keyword,
          range: range,
          detail: 'SQL关键字'
        })
      })

      // 添加函数补全
      sqlFunctions.forEach(func => {
        suggestions.push({
          label: func,
          kind: monaco.languages.CompletionItemKind.Function,
          insertText: `${func}()`,
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          range: range,
          detail: 'SQL函数'
        })
      })

      // 添加数据类型补全
      sqlTypes.forEach(type => {
        suggestions.push({
          label: type,
          kind: monaco.languages.CompletionItemKind.TypeParameter,
          insertText: type,
          range: range,
          detail: 'SQL数据类型'
        })
      })

      // 添加基础SQL语句模板（保守方案 - 5个核心模板）
      const templates = [
        {
          label: 'select-basic',
          kind: monaco.languages.CompletionItemKind.Snippet,
          insertText: 'SELECT ${1:*} FROM ${2:table_name};',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          range: range,
          detail: '基础查询模板',
          documentation: 'SELECT查询语句模板'
        },
        {
          label: 'select-where',
          kind: monaco.languages.CompletionItemKind.Snippet,
          insertText: 'SELECT ${1:*} FROM ${2:table_name} WHERE ${3:condition};',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          range: range,
          detail: '条件查询模板',
          documentation: '带WHERE条件的SELECT查询'
        },
        {
          label: 'insert-basic',
          kind: monaco.languages.CompletionItemKind.Snippet,
          insertText: 'INSERT INTO ${1:table_name} (${2:columns}) VALUES (${3:values});',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          range: range,
          detail: '插入数据模板',
          documentation: 'INSERT插入语句模板'
        },
        {
          label: 'update-basic',
          kind: monaco.languages.CompletionItemKind.Snippet,
          insertText: 'UPDATE ${1:table_name} SET ${2:column} = ${3:value} WHERE ${4:condition};',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          range: range,
          detail: '更新数据模板',
          documentation: 'UPDATE更新语句模板'
        },
        {
          label: 'delete-basic',
          kind: monaco.languages.CompletionItemKind.Snippet,
          insertText: 'DELETE FROM ${1:table_name} WHERE ${2:condition};',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          range: range,
          detail: '删除数据模板',
          documentation: 'DELETE删除语句模板'
        }
      ]

      suggestions.push(...templates)

      return { suggestions }
    }
  })

  console.log('基础SQL语言支持注册完成 - 保守方案')
}

// 计算属性
const lineCount = computed(() => {
  return props.modelValue ? props.modelValue.split('\n').length : 0
})

// 初始化编辑器
const initEditor = async () => {
  try {
    loading.value = true
    
    // 等待DOM渲染完成
    await nextTick()
    
    if (!editorContainer.value) {
      throw new Error('编辑器容器未找到')
    }

    // 使用Monaco Editor Loader
    const monaco = await loader.init()
    
    // 注册基础SQL语言支持
    registerBasicSQLLanguage(monaco)

    // 创建编辑器实例
    editorInstance = monaco.editor.create(editorContainer.value, {
      value: props.modelValue || props.placeholder,
      language: 'sql',
      theme: 'vs-dark', // 深色主题
      automaticLayout: true,
      minimap: { enabled: false },
      scrollBeyondLastLine: false,
      wordWrap: 'on',
      lineNumbers: 'on',
      fontSize: 14,
      fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
      tabSize: 2,
      insertSpaces: true,
      // 增强编辑体验
      suggestOnTriggerCharacters: true,
      quickSuggestions: {
        other: true,
        comments: false,
        strings: false
      },
      // 确保编辑器正确布局
      dimension: {
        width: editorContainer.value.clientWidth,
        height: editorContainer.value.clientHeight
      }
    })
    
    // 设置初始值
    if (props.modelValue) {
      editorInstance.setValue(props.modelValue)
    }

    // 监听内容变化
    editorInstance.onDidChangeModelContent(() => {
      const value = editorInstance.getValue()
      emit('update:modelValue', value)
      emit('change', value)
    })

    // 延迟布局确保正确显示
    setTimeout(() => {
      if (editorInstance) {
        editorInstance.layout()
      }
    }, 100)

    // 添加resize监听器
    const resizeObserver = new ResizeObserver(() => {
      if (editorInstance) {
        editorInstance.layout()
      }
    })
    resizeObserver.observe(editorContainer.value)

    // 窗口resize时也重新布局
    const handleResize = () => {
      if (editorInstance) {
        setTimeout(() => {
          editorInstance.layout()
        }, 100)
      }
    }
    window.addEventListener('resize', handleResize)

    // 保存清理函数
    editorInstance._resizeObserver = resizeObserver
    editorInstance._handleResize = handleResize

    editorReady.value = true
    loading.value = false

    emit('ready', editorInstance)

    console.log('简化SQL编辑器初始化成功')

  } catch (error) {
    console.error('初始化SQL编辑器失败:', error)
    ElMessage.error(`编辑器初始化失败: ${error.message}`)
    loading.value = false
  }
}

// 格式化SQL
const formatSQL = async () => {
  if (!editorInstance || loading.value) return

  try {
    const value = editorInstance.getValue()
    // 简单的SQL格式化
    const formatted = value
      .replace(/\s+/g, ' ')
      .replace(/\bSELECT\b/gi, 'SELECT')
      .replace(/\bFROM\b/gi, '\nFROM')
      .replace(/\bWHERE\b/gi, '\nWHERE')
      .replace(/\bAND\b/gi, '\n  AND')
      .replace(/\bOR\b/gi, '\n  OR')
      .trim()
    
    editorInstance.setValue(formatted)
    ElMessage.success('SQL格式化完成')
  } catch (error) {
    console.error('SQL格式化失败:', error)
    ElMessage.warning('格式化失败')
  }
}

// 清空编辑器
const clearEditor = () => {
  if (!editorInstance || loading.value) return
  
  editorInstance.setValue('')
  editorInstance.focus()
  ElMessage.success('编辑器已清空')
}

// 拖拽调整编辑器高度
const startResize = (e) => {
  console.log('开始拖拽调整编辑器高度', { startY: e.clientY, currentHeight: editorHeight.value })

  isResizing.value = true
  startY = e.clientY
  startHeight = editorHeight.value

  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  document.body.style.cursor = 'ns-resize'
  document.body.style.userSelect = 'none'

  // 阻止默认行为
  e.preventDefault()
}

const handleResize = (e) => {
  if (!isResizing.value) return

  const deltaY = e.clientY - startY
  const newHeight = Math.max(60, Math.min(800, startHeight + deltaY)) // 最小60px（约一行高度）

  console.log('拖拽调整中', { deltaY, newHeight, currentY: e.clientY })

  editorHeight.value = newHeight

  // 重新布局编辑器
  if (editorInstance) {
    setTimeout(() => {
      editorInstance.layout()

      // 在迷你模式下优化显示
      if (editorHeight.value <= 100) {
        editorInstance.updateOptions({
          lineNumbers: 'off',        // 隐藏行号
          folding: false,           // 禁用代码折叠
          lineDecorationsWidth: 0,  // 移除行装饰宽度
          lineNumbersMinChars: 0,   // 最小行号字符数
          glyphMargin: false,       // 隐藏字形边距
          scrollBeyondLastLine: false
        })
      } else {
        editorInstance.updateOptions({
          lineNumbers: 'on',        // 显示行号
          folding: true,           // 启用代码折叠
          lineDecorationsWidth: 10, // 恢复行装饰宽度
          lineNumbersMinChars: 3,   // 恢复行号字符数
          glyphMargin: true,        // 显示字形边距
          scrollBeyondLastLine: false
        })
      }
    }, 0)
  }
}

const stopResize = () => {
  console.log('结束拖拽调整', { finalHeight: editorHeight.value })

  isResizing.value = false
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  document.body.style.cursor = ''
  document.body.style.userSelect = ''

  // 保存用户偏好到localStorage
  localStorage.setItem('sql-editor-height', editorHeight.value.toString())
}

// 从localStorage恢复编辑器高度
const restoreEditorHeight = () => {
  const savedHeight = localStorage.getItem('sql-editor-height')
  if (savedHeight) {
    editorHeight.value = parseInt(savedHeight, 10)
  } else {
    // 如果没有保存的高度，使用props中的height作为初始值
    const heightValue = parseInt(props.height) || 400
    editorHeight.value = heightValue
  }
}

// 设置编辑器预设尺寸
const setEditorSize = (size) => {
  const sizes = {
    mini: 80,    // 迷你尺寸 - 约一行高度
    small: 200,  // 小尺寸
    medium: 400, // 中尺寸
    large: 600   // 大尺寸
  }

  editorHeight.value = sizes[size] || 400

  // 重新布局编辑器
  if (editorInstance) {
    setTimeout(() => {
      editorInstance.layout()

      // 在迷你模式下优化显示
      if (editorHeight.value <= 100) {
        editorInstance.updateOptions({
          lineNumbers: 'off',        // 隐藏行号
          folding: false,           // 禁用代码折叠
          lineDecorationsWidth: 0,  // 移除行装饰宽度
          lineNumbersMinChars: 0,   // 最小行号字符数
          glyphMargin: false,       // 隐藏字形边距
          scrollBeyondLastLine: false
        })
      } else {
        editorInstance.updateOptions({
          lineNumbers: 'on',        // 显示行号
          folding: true,           // 启用代码折叠
          lineDecorationsWidth: 10, // 恢复行装饰宽度
          lineNumbersMinChars: 3,   // 恢复行号字符数
          glyphMargin: true,        // 显示字形边距
          scrollBeyondLastLine: false
        })
      }
    }, 0)
  }

  // 保存用户偏好
  localStorage.setItem('sql-editor-height', editorHeight.value.toString())

  const sizeNames = {
    mini: '迷你',
    small: '小',
    medium: '中',
    large: '大'
  }

  ElMessage.success(`编辑器尺寸已调整为${sizeNames[size]}尺寸 (${editorHeight.value}px)`)
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (editorInstance && newValue !== editorInstance.getValue()) {
    editorInstance.setValue(newValue || '')
  }
})

// 生命周期
onMounted(() => {
  restoreEditorHeight() // 恢复用户偏好的编辑器高度
  initEditor()
})

onBeforeUnmount(() => {
  if (editorInstance) {
    // 清理resize监听器
    if (editorInstance._resizeObserver) {
      editorInstance._resizeObserver.disconnect()
    }
    if (editorInstance._handleResize) {
      window.removeEventListener('resize', editorInstance._handleResize)
    }

    // 销毁编辑器实例
    editorInstance.dispose()
  }
})

// 暴露方法给父组件
defineExpose({
  getEditor: () => editorInstance,
  getValue: () => editorInstance?.getValue() || '',
  setValue: (value) => editorInstance?.setValue(value || ''),
  focus: () => editorInstance?.focus(),
  formatSQL,
  clearEditor,
  setHeight: (height) => {
    editorHeight.value = Math.max(60, Math.min(800, height)) // 最小60px
    if (editorInstance) {
      setTimeout(() => editorInstance.layout(), 0)
    }
  },
  getHeight: () => editorHeight.value
})
</script>

<style scoped>
.simple-sql-editor {
  display: flex;
  flex-direction: column;
  border: 1px solid #3c3c3c; /* 深色主题边框 */
  border-radius: 4px;
  overflow: hidden;
  background: #1e1e1e; /* 深色主题背景 */
  height: 100%; /* 确保组件占满父容器 */
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #2d2d30; /* 深色主题工具栏 */
  border-bottom: 1px solid #3c3c3c;
  min-height: 40px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.editor-container {
  /* 移除 flex: 1，使用具体高度 */
  position: relative;
  overflow: hidden;
  /* 高度由 :style 绑定的 editorHeight 控制 */
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 12px;
  background: #2d2d30; /* 深色主题状态栏 */
  border-top: 1px solid #3c3c3c;
  font-size: 12px;
  color: #cccccc; /* 深色主题文字颜色 */
  min-height: 28px;
}

.footer-left,
.footer-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.editor-info {
  font-size: 12px;
  color: #909399;
}

/* 拖拽调整条样式 - 更明显的设计 */
.resize-handle {
  height: 16px;
  background: linear-gradient(to bottom, #3c3c3c, #2d2d30, #3c3c3c);
  border-top: 1px solid #555;
  border-bottom: 1px solid #555;
  cursor: ns-resize;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  position: relative;
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
}

.resize-handle:hover {
  background: linear-gradient(to bottom, #555, #404040, #555);
  border-color: #777;
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.2);
}

.resize-handle::before {
  content: '⋮⋮⋮⋮⋮';
  color: #888;
  font-size: 14px;
  letter-spacing: 3px;
  transition: color 0.2s;
  text-shadow: 0 1px 0 rgba(0,0,0,0.5);
}

.resize-handle:hover::before {
  color: #aaa;
}

.resize-line {
  width: 80px;
  height: 4px;
  background: linear-gradient(to right, transparent, #888, transparent);
  border-radius: 2px;
  position: relative;
  opacity: 0.8;
}

.resize-line::before,
.resize-line::after {
  content: '';
  position: absolute;
  width: 60px;
  height: 1px;
  background: linear-gradient(to right, transparent, #666, transparent);
  left: 10px;
}

.resize-line::before {
  top: -3px;
}

.resize-line::after {
  bottom: -3px;
}

.resize-handle:hover .resize-line {
  background: linear-gradient(to right, transparent, #aaa, transparent);
  opacity: 1;
}

.resize-handle:hover .resize-line::before,
.resize-handle:hover .resize-line::after {
  background: linear-gradient(to right, transparent, #888, transparent);
}

/* 添加拖拽时的视觉反馈 */
.resize-handle:active {
  background: linear-gradient(to bottom, #666, #555, #666);
  border-color: #888;
}

.resize-handle:active::before {
  color: #ccc;
}

/* 深色主题适配 */
.editor-info {
  font-size: 12px;
  color: #cccccc; /* 深色主题下的文字颜色 */
}
</style>
